<?php


namespace app\admin\controller;


use app\admin\model\Role;
use app\admin\model\User;
use app\admin\validate\UserValidate;
use think\facade\View;

class UserController extends Base
{

    private $status = ['1' => '正常', '2' => '禁用'];

    /**
     * 用户列表
     *
     * @param User $user
     * @return string|\think\response\Json
     */
    public function index(User $user)
    {
        if (request()->isAjax()) {

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
            }
            $selectResult = $user->getUsersByWhere($where, $offset, $limit);

            $selectResult->each(function ($v) {
                $v['last_login_time'] = date('Y-m-d H:i:s', $v['last_login_time']);
                $v['status'] = $this->status[$v['status']];
                if (1 == $v['id']) {
                    $v['operate'] = '';
                    return false;
                }

                $v['operate'] = showOperate($this->makeButton($v['id']));

            });


            $return['total'] = $user->getAllUsers($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }

        return View::fetch();
    }

    /**
     * 添加用户
     *
     * @param User $userModel
     * @param UserValidate $userValidate
     * @return string
     */
    public function userAdd(User $userModel, UserValidate $userValidate)
    {

        if (request()->isAjax()) {

            $param = request()->param();

            $isValid = $userValidate->check($param);
            if (!$isValid) {
                $this->error($userValidate->getError());
            }

            $res = $userModel->save($param);

            if ($res) {
                $this->success('添加成功', (string)url('user/index'));
            } else {
                $this->error('添加失败');
            }

        }

        $role = new Role();

        View::assign([
            'role' => $role->getRole(),
            'status' => $this->status
        ]);

        return View::fetch();

    }

    /**
     * 编辑用户
     *
     * @param User $user
     * @param Role $role
     * @return string
     */
    public function userEdit(User $user, Role $role)
    {

        if (request()->isPost()) {

            $param = request()->param();

            if (empty($param['password'])) {
                unset($param['password']);
            }
            $res = $user::update($param, ['id' => $param['id']]);

            if ($res) {
                $this->success('删除成功', (string)url('user/index'));
            } else {
                $this->error('删除失败');
            }
        }

        $id = request()->param('id');

        View::assign([
            'user' => $user::find($id),
            'status' => config('user_status'),
            'role' => $role->getRole()
        ]);
        return View::fetch();
    }

    /**
     * 删除管理员
     *
     * @param User $user
     * @return \think\response\Json
     */
    public function userDel(User $user)
    {
        $id = input('param.id');

        $res = $user::destroy($id);
        if ($res) {
            $this->success('删除成功', (string)url('user/index'));
        } else {
            $this->error('删除失败');
        }
    }


    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        return [
            '编辑' => [
                'auth' => 'user/useredit',
                'href' => url('user/userEdit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '删除' => [
                'auth' => 'user/userdel',
                'href' => "javascript:userDel(" . $id . ")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ]
        ];
    }

}